package com.cz.design.structure.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy {
    public static <T> T createProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();

        // 设置要增强哪个类的功能。增强器为这个类动态创建一个子类
        enhancer.setSuperclass(clazz);

        // 设置回调，
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                // 编写拦截的逻辑
                System.out.println("cglib执行了...xxx");

                // 目标方法执行
                Object invoke = methodProxy.invokeSuper(o, objects);
                return invoke;
            }
        });

        return (T) enhancer.create();

    }
}
